package jobs;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import domain.Tweet;
import domain.User;

public class TweetProcessor {

	
	public static class TweetMapper extends
			Mapper<User, Tweet, User, IntWritable> {

		public void map(User key, Tweet value, Context context)
				throws IOException, InterruptedException {
			if(value.getUser().getLang().equals("en")){
				if(value.getText().contains("apple") ||value.getText().contains("ios") ||value.getText().contains("itunes") ||value.getText().contains("google") ||value.getText().contains("android") ||value.getText().contains("gmail") ||value.getText().contains("microsoft") ||value.getText().contains("windows") || value.getText().contains("hotmail")){
					context.write(key, new IntWritable(1));
				}	
			}	
		}
	}

	public static class TweetReducer extends
			Reducer<User, IntWritable, User, IntWritable> {
		private IntWritable result = new IntWritable();

		public void reduce(User key, Iterable<IntWritable> values,
				Context context) throws IOException, InterruptedException {
			int sum = 0;
			for (IntWritable val : values) {
				sum = sum + val.get();
			}
			result.set(sum);
			context.write(key, result);
		}
	}

	public static void main(String[] args) throws Exception {
		Configuration conf = new Configuration();
		Job job = new Job(conf, "Tweet Processor");
		job.setJarByClass(TweetProcessor.class);
		job.setMapperClass(TweetMapper.class);
		job.setCombinerClass(TweetReducer.class);
		job.setReducerClass(TweetReducer.class);
		job.setOutputKeyClass(User.class);
		job.setOutputValueClass(IntWritable.class);
		job.setInputFormatClass(TweetInputFormat.class);
		FileInputFormat.addInputPath(job, new Path(args[0]));   
		FileOutputFormat.setOutputPath(job, new Path(args[1]));  
		System.exit(job.waitForCompletion(true) ? 0 : 1);
	}
}
